<?php


namespace console\controllers;


use common\models\MemberDiscountCoupon;
use yii\console\Controller;

class TaskController extends Controller
{
    /**
     * 用户优惠券有效期状态自动变更
     */
    public function actionIndex()
    {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            foreach (MemberDiscountCoupon::find()->where(['<>', 'status', 10])->each(100) as $model) {
                /* @var $model MemberDiscountCoupon */
                if(($model->discountCoupon->start_date > time() || $model->discountCoupon->end_date < time()) && $model->status == 0) {
                    $model->status = 20;
                }

                if(($model->discountCoupon->start_date < time() && $model->discountCoupon->end_date > time()) && $model->status == 20) {
                    $model->status = 0;
                }
                $model->updated_at = time();
                if(!$model->save(false)) {
                    throw new \Exception("优惠券状态编辑失败：". current($model->getFirstErrors()));
                }
            }
            $trans->commit();
            echo "执行成功" . PHP_EOL;
        } catch (\Exception $e) {
            $trans->rollBack();
            \Yii::error("执行任务失败：" . $e->getMessage() . $e->getTraceAsString());
            echo "执行任务失败" . $e->getMessage() . PHP_EOL;
        }
    }
}